<template>
  <div class="card">
    <div class="title-sign">库存盘点</div>
    <!--   【1】盘点条件   -->
    <CountModule ref="countModuleRef" @system-random="getSystemRandomFn" @range-change="rangeChangeFn" />

    <template v-if="!id && countModuleRef?.countData?.selectType === 2 && countModuleRef?.countData?.type !== 4">
      <div class="title-sign">选择样本</div>
      <!--   【2】搜索条件   -->
      <SampleModule ref="sampleModuleRef" :range="state.storageIds" @checked-change="checkedChangeFn" />
    </template>

    <div class="title-sign">已选样本</div>
    <div style="margin: 10px 21px">
      已选样本数量
      <span class="num">{{ sampleSize }}</span>
      支
    </div>
    <!--   【3】tab   -->
    <Tabs v-model:activeKey="state.activeKey" type="card" hideAdd @edit="editTabFn">
      <template #rightExtra>
        <Space>
          <Button :disabled="!!id || sampleSize === 0" type="blue-white" @click="createCountFn(1)">手动盘点</Button>
          <Button :disabled="!!id || sampleSize === 0" type="blue-white" @click="createCountFn(2)">自动盘点</Button>
        </Space>
      </template>
      <TabPane v-for="(item, index) in [...state.checkedMap]" :key="index" :tab="item[0]?.serial" />
    </Tabs>
    <!--   【4】标题   -->
    <Space :size="50" style="margin: 5px 0">
      <div>冻存盒编号：{{ curData[0]?.serial ?? '-' }}</div>
      <div>冻存盒类型：{{ curData[0]?.boxType ?? '-' }}</div>
      <div>冻存盒状态：{{ getStateFn(curData[0]?.status) }}</div>
      <div>冻存盒位置：{{ curData[0]?.storageDesp ?? '-' }}</div>
      <div>已存放支数：{{ curData[0]?.subSpecimens?.length ?? '-' }}</div>
      <div>剩余孔位数：{{ curData[0]?.boxCols && curData[0]?.boxRows && curData[0]?.subSpecimens?.length ? curData[0]?.boxCols *
        curData[0]?.boxRows - curData[0]?.subSpecimens?.length : '-' }}</div>
      <div>项目组：{{ curData[0]?.projectName ?? '-' }}</div>
    </Space>
    <!--   【5】图形表格   -->
    <div class="box-table">
      <StorageBox :cols="curData[0]?.boxCols" :row="curData[0]?.boxRows" :draggable="true" :list="curData[1]"
        :scale="0.7" />
      <div style="flex: 1">
        <a-progress v-if="state.inventoryState > 2" stroke-linecap="square"
          :percent="(curData[1]?.filter((item) => item.status === 1)?.length / curData[1]?.length) * 100"
          :strokeWidth="10" :show-info="false" trailColor="#ccc" :stroke-color="{ from: '#108ee9', to: '#87d068' }"
          status="active" />
        <vxe-table ref="tableRef" height="auto" align="center" round stripe :data="curData[1]" size="mini">
          <vxe-column field="sortIndex" title="位置"
            :formatter="({ cellValue }) => subscript(cellValue, curData[0]?.boxRows)" />
          <vxe-column field="originalSerial" title="样本编号" />
          <vxe-column field="name" title="样本名称" />
          <vxe-column field="sampleTime" title="采样日期" />
          <vxe-column field="serial" title="数字编号" />
          <vxe-column field="capacity" title="容量" :formatter="({ cellValue, row }) => `${cellValue}${row.countUnit}`" />
          <vxe-column field="status" title="盘点">
            <template #default="{ row }">
              <svg v-if="row.status === 1" t="1680592527152" class="icon" viewBox="0 0 1024 1024" version="1.1"
                xmlns="http://www.w3.org/2000/svg" p-id="2909" width="45" height="20">
                <path
                  d="M512.024381 0C229.205333 0 0 229.205333 0 512.024381 0 794.770286 229.205333 1024 512.024381 1024 794.770286 1024 1024 794.770286 1024 512.024381 1024 229.205333 794.770286 0 512.024381 0M849.603048 353.328762l-385.462857 385.462857c-9.411048 9.411048-21.723429 14.09219-34.06019 14.09219s-24.697905-4.681143-34.084571-14.09219l-221.622857-221.647238c-18.822095-18.822095-18.822095-49.322667 0-68.120381 18.822095-18.846476 49.322667-18.846476 68.144762 0l187.562667 187.562667 351.378286-351.402667c18.822095-18.822095 49.322667-18.822095 68.144762 0C868.425143 304.006095 868.425143 334.506667 849.603048 353.328762"
                  fill="#5bdc9c" p-id="2910" data-spm-anchor-id="a313x.7781069.0.i0" class="" />
              </svg>
              <svg v-else t="1680592590083" class="icon" viewBox="0 0 1024 1024" version="1.1"
                xmlns="http://www.w3.org/2000/svg" p-id="3923" width="45" height="20">
                <path
                  d="M512 981.333333C252.8 981.333333 42.666667 771.2 42.666667 512S252.8 42.666667 512 42.666667s469.333333 210.133333 469.333333 469.333333-210.133333 469.333333-469.333333 469.333333z m44.245333-469.333333l159.914667-159.914667a31.274667 31.274667 0 1 0-44.245333-44.245333L512 467.754667 352.085333 307.84a31.274667 31.274667 0 1 0-44.245333 44.245333L467.754667 512l-159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333 44.245333L512 556.245333l159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333-44.245333L556.245333 512z"
                  fill="#F5222D" p-id="3924" />
              </svg>
            </template>
          </vxe-column>
          <vxe-column title="操作">
            <template #default="{ row }">
              <Button :disabled="!!id || countModuleRef?.countData?.type === 4" type="blue-white" size="small"
                @click="delSampleFn(curData[0], row)">移除</Button>
            </template>
          </vxe-column>
        </vxe-table>
        <Space style="display: flex; justify-content: center; padding: 5px" :size="80">
          <Button :disabled="!!id" @click="resetFn">重置</Button>
          <Button :disabled="!id || state.inventoryState < 9" type="blue-white"
            @click="state.showHighCamera = true">下一步</Button>
        </Space>
      </div>
    </div>

    <!--   【6】盘点单   -->
    <InventoryList :inventoryType="state.inventoryType" :countData="countModuleRef?.countData"
      v-model:show-drawer="state.showListDrawer" :map="state.checkedMap" :size="sampleSize" @drawer-ok="startCountFn" />
    <!--   【7】底单存档   -->
    <Modal :destroyOnClose="true" :maskClosable="false" :footer="null" title="底单存档" width="60%"
      v-model:visible="state.showHighCamera">
      <HighCameracopy highCameraId="inputManageHighCamera" canvasCameraId="inputManageCanvasCamera" :router-record="true"
        :processCfg="state.processCfg" :billId="id" :billType="4" @upload-success="uploadSuccess" />
    </Modal>
  </div>
</template>

<script setup lang="ts">
import CountModule from '@/modules/sample-inventory/pages/inventory-count/components/count-module.vue';
import SampleModule from '@/modules/sample-inventory/pages/inventory-count/components/sample-module.vue';
import InventoryList from '@/modules/sample-inventory/pages/inventory-count/components/inventory-list.vue';
import HighCameracopy from '@/components/photograph/HighCameracopy.vue';
import { Tabs, TabPane, Space, message, Modal } from 'ant-design-vue';
import { computed, reactive, ref, onBeforeUnmount, nextTick } from 'vue';
import Button from '@/framework/components/basic/button/button.vue';
import { subscript } from '@/libs/utils';
import StorageBox from '@/modules/underlying-data/pages/storage-management/components/storage-box/storage-box.vue';
import type { VxeTableInstance } from 'vxe-table';
import { useRoute } from 'vue-router';
import { createInventory, getInventoryDetail, inventoryFix, submitInventory } from '@/modules/sample-inventory/api';
import router from '@/router';
import { userSearch } from '@/api/operationFlow';
import MQTT from '@/framework/utils/mqtt';
type State = {
  inventoryLoading: boolean;
  storageIds: any[];
  checkedMap: any;
  activeKey: number;
  showListDrawer: boolean;
  showHighCamera: boolean;
  inventoryType: 1 | 2;
  inventoryState: 1 | 2 | 3 | 9 | 10;
  processCfg: any;
};
const state: State = reactive({
  inventoryLoading: false,
  storageIds: [],
  checkedMap: new Map(),
  activeKey: 0,
  showListDrawer: false,
  showHighCamera: false,
  inventoryType: 1,
  inventoryState: '',
  processCfg: {
    isArchive: true, //是否开启底单存档文件上传
    isCapture: true, //是否开启高拍仪
    isSignature: true, //是否开启电子签名
  },
});
const route = useRoute();
const id = route.params.id;
const countModuleRef = ref();
const sampleModuleRef = ref();
const tableRef = ref<VxeTableInstance>();

// 当前tab页数据
const curData = computed<[any[], any[]][]>(() => {
  return [...state.checkedMap][state.activeKey] ?? [];
});
// 选中样本总数
const sampleSize = computed(() => {
  return [...state.checkedMap].reduce((previousValue, currentValue) => {
    if (!currentValue[1]) return previousValue;
    return (previousValue += currentValue[1]?.length);
  }, 0);
});

// 范围变化
const rangeChangeFn = (list) => {
  state.storageIds = list;
};
const getStateFn = (value) => {
  switch (value) {
    case 1:
      return '未入库';
    case 2:
      return '已入库';
    case 3:
      return '已出库';
    case 4:
      return '正在入库';
    case 5:
      return '正在出库';
    default:
      return '-';
  }
};

/**
 * 盘点
 */
// 确认盘点单
const createCountFn = (type) => {
  let countConfig = countModuleRef.value?.countData;
  if (!countConfig.name || !countConfig.creatorName) {
    return message.warn('请完善基础信息!');
  }
  state.showListDrawer = true;
  state.inventoryType = type;
};
// 生成盘点单
const startCountFn = async () => {
  if (state.inventoryLoading) return;
  state.inventoryLoading = true;
  let countConfig = countModuleRef.value?.countData;
  const stocks = [...state.checkedMap].map((item) => {
    if (!item || item.length === 0) return;
    if (countConfig.type === 3 || item[0].isNotAll || (item[0].type === 4 && countConfig.wholeBox === 0)) {
      // 非整盒
      return {
        linkId: item[0].linkId,
        subSpecimens: item[1].map((sub) => ({ id: sub.id })),
      };
    } else {
      return {
        linkId: item[0].linkId,
      };
    }
  });

  let data = {
    batchNo: countConfig.batchNo,
    name: countConfig.name,
    creatorName: countConfig.creatorName,
    storageIds: countConfig.storageIds ?? [],
    stocks,
    type: String(countConfig.type ?? ''),
    selectType: countConfig.type === '4' ? 0 : countConfig.selectType,
  };
  // 【1】生成盘点单
  const res = await createInventory(data);
  if (state.inventoryType === 1) {
    const sub = await getInventoryDetail(res.result);
    // 手动盘点
    const submitData = {
      id: sub.result.id,
      inventorierName: data.name,
      stocks,
    };
    submitData.stocks = sub.result.stocks.map((item) => {
      if (item.type === 4 && item.wholeBox === 0) {
        // 非整盒
        return {
          linkId: item.linkId,
          subSpecimens: item.subSpecimens.map((sub) => ({
            id: sub.id,
            status: 1,
          })),
        };
      } else {
        return {
          linkId: item.linkId,
          submitStatus: 1,
        };
      }
    });
    // 提交盘点单
    await submitInventory(submitData);
  }
  await router.push({
    name: 'inventoryCountDetail',
    params: {
      id: res.result,
    },
  });
  state.inventoryLoading = false;
};

/**
 * 底单存档完成
 */
const uploadSuccess = () => {
  state.showHighCamera = false;
};

/**
 * 表格数据联动
 */
// 重置
const resetFn = () => {
  state.checkedMap.clear();
  sampleModuleRef.value?.changeCheckedStateFn(state.checkedMap);
  countModuleRef.value?.setCountData({
    batchNo: countModuleRef.value?.countData.batchNo,
    selectType: 2,
    type: 1,
  });
};
// 条件变动修改数据
const getSystemRandomFn = (list) => {
  state.checkedMap.clear();
  if (!list) return;
  list?.forEach((item) => {
    // if (item.type === 3) return;
    state.checkedMap.set(item, item.subSpecimens);
  });
  console.log(state.checkedMap);
};
// 选中项
const checkedChangeFn = (map) => {
  if (id) return;
  state.checkedMap = map;
};
// 删除tab
const editTabFn = (targetKey, action) => {
  if (action !== 'remove' || id) return;
  if (Number(targetKey) > 0) {
    state.activeKey--;
  }
  let activeKey = [...state.checkedMap][targetKey][0];
  state.checkedMap.delete(activeKey);
  sampleModuleRef.value?.changeCheckedStateFn(state.checkedMap, activeKey);
};
// 移除子项
const delSampleFn = (key, row) => {
  let activeKey = [...state.checkedMap][state.activeKey][0];
  if (state.checkedMap.get(key)?.length <= 1) {
    state.checkedMap.delete(key);
  } else {
    let index = state.checkedMap.get(key)?.findIndex((item) => item === row);
    state.checkedMap.get(key)?.splice(index, 1);
    tableRef.value?.reloadData(state.checkedMap.get(key));
  }
  sampleModuleRef.value?.changeCheckedStateFn(state.checkedMap, activeKey);
};

/**
 * 获取权限
 */
const getPermissionsFn = async (type, specimenOutableVoList) => {
  const res = await userSearch({ type, specimenOutableVoList });
  state.processCfg.isArchive = res.result.processCfg.isArchive;
  state.processCfg.isCapture = res.result.processCfg.isCapture;
  state.processCfg.isSignature = res.result.processCfg.isSignature;
};

/**
 * id存在执行
 */
const init = async () => {
  // id不存在跳出
  if (!id) return;
  // 获取盘点单详情
  const res = await getInventoryDetail(id);
  // 替换值
  state.checkedMap.clear();
  res.result?.stocks?.forEach((item) => {
    state.checkedMap.set(item, item.subSpecimens);
  });
  // 没用
  countModuleRef.value?.setCountData(res.result);
  // 存状态
  state.inventoryState = res.result.status;
  // 权限
  const list = res.result?.stocks?.reduce((pre, cur) => {
    pre.push(...cur.subSpecimens);
    return pre;
  }, []);
  await getPermissionsFn(7, list);

  let modal;

  switch (res.result.status) {
    case 1:
    case 2:
      MQTT.subscribe('bill-inventory-status', 0);
      MQTT.$on('mqtt-msg', (res) => {
        const { data } = JSON.parse(res.msg.toString());
        if (Number(data) === Number(id)) {
          Modal.destroyAll();
          nextTick(async () => {
            MQTT.unsubscribe('bill-inventory-status');
            await init();
          });
        }
      });
      modal = Modal.info({
        centered: true,
        title: '盘点中',
        closable: false,
        content: `${sampleSize.value}支样本正在盘点中`,
        okText: '查看记录',
        onOk: () => {
          router.push({ name: 'inventoryRecords' });
          modal.destroy();
        },
      });
      break;
    case 3:
      const failNum = res.result?.stocks?.reduce((pre, cur) => {
        if (cur.subSpecimens) {
          pre += cur.subSpecimens?.filter((item) => item?.status === 2)?.length;
        }
        return pre;
      }, 0);
      const reload = async () => {
        const sub = await getInventoryDetail(id);
        state.checkedMap.clear();
        sub.result?.stocks?.forEach((item) => {
          state.checkedMap.set(item, item.subSpecimens);
        });
        state.inventoryState = sub.result.status;
      };
      const data = { id, stocks: {} };
      modal = Modal.confirm({
        centered: true,
        title: '失败',
        closable: false,
        content: `${failNum}支样本盘点失败，请选择下一步操作：`,
        cancelText: '手动确认',
        onCancel: async () => {
          data.stocks = res.result?.stocks?.map((item) => {
            if (item.type === 4 && item.wholeBox === 0) {
              // 非整盒
              return {
                linkId: item.linkId,
                subSpecimens: item.subSpecimens.map((sub) => ({
                  id: sub.id,
                  status: 1,
                })),
              };
            } else {
              return {
                linkId: item.linkId,
                submitStatus: 1,
              };
            }
          });
          await submitInventory(data);
          await reload();
          modal.destroy();
        },
        okText: '确认结果',
        onOk: async () => {
          data.stocks = res.result?.stocks?.map((item) => {
            if (item.type === 4 && item.wholeBox === 0) {
              // 非整盒
              return {
                linkId: item.linkId,
                subSpecimens: item.subSpecimens.map((sub) => ({
                  id: sub.id,
                  status: 2,
                  memo: '',
                })),
              };
            } else {
              return {
                linkId: item.linkId,
                submitStatus: 2,
                memo: '',
              };
            }
          });
          await inventoryFix(data);
          await reload();
          modal.destroy();
        },
      });

      break;
    case 9:
      modal = Modal.success({
        centered: true,
        title: '盘点完成',
        closable: false,
        content: `${sampleSize.value}支样本已全部盘点完成！`,
        onOk: () => {
          modal.destroy();
          MQTT.publish('bims/pad/share/taskpush', '{"on":false}');
        },
      });
      break;
    default:
      break;
  }
};
router.beforeEach((to, from, next) => {
  if (to.meta.title != '库存盘点') {
    MQTT.publish('bims/pad/share/taskpush', '{"on":false}');
  }
  next()
})
init();
</script>

<style scoped lang="less">
.title-sign {
  margin: 5px 0 5px;
  font-size: 18px;
}

.box-table {
  display: flex;
  height: 288px;
}

.num {
  width: 18px;
  color: rgba(50, 145, 248, 100);
  font-size: 28px;
  line-height: 0;
}

.card {
  :deep(.ant-tabs-card.ant-tabs-top) {
    >.ant-tabs-nav {
      .ant-tabs-tab {
        border-radius: 7px 7px 0 0;
        height: 32px;
        background-color: #efefef;
      }

      .ant-tabs-tab-active {
        background-color: #83bcf9;
        border-radius: 7px 7px 0 0;
        height: 32px;
      }

      &::before {
        border: none;
      }
    }
  }
}

.icon {
  margin: auto;
}
</style>
